import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:getx_scaffold/common/common.dart';
import 'package:getx_scaffold/common/index.dart';
import 'package:oramemo/common/config/app_config.dart';
import 'package:oramemo/core/config/api_config.dart';
import 'package:oramemo/core/network/dio_client.dart';
import 'package:oramemo/entity/upload_entity.dart';
import 'package:path_provider/path_provider.dart';
import 'package:oramemo/common/langs/text_key.dart';

class AudioUploader {
  bool _isUploading = false;
  double _progress = 0;
  CancelToken? _cancelToken;
  final DioClient _client = DioClient();

  Future<bool> uploadFile(String audioPath) async {
    _isUploading = true;
    _progress = 0;
    _cancelToken = CancelToken();
    bool isSuccess = false;

    try {
      final formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(
          audioPath,
          filename: audioPath.split('/').last,
        ),
      });
      showLoading(TextKey.audioUploadInProgress.tr);
      final response = await _client.request(
        method: 'POST',
        path: ApiConfig.uploadFile,
        data: formData,
        cancelToken: _cancelToken,
      );
      dismissLoading();
      if (response.data != null) {
        final result = UploadEntity.fromJson(response.data);
        if (result.code == 200 && result.url?.isNotEmpty == true) {
          showSuccessToast(TextKey.audioUploadSuccess.tr);
          isSuccess = true;
        } else {
          showToast(TextKey.audioUploadError.tr);
        }
      }
    } on DioException catch (e) {
      showToast(TextKey.audioUploadError.tr);
    } finally {
      _isUploading = false;
      _cancelToken = null;
    }
    return isSuccess;
  }

  void cancelUpload() {
    _cancelToken?.cancel('Upload cancelled by user');
  }
}
